<script setup>
import { ref, onMounted, watch } from 'vue'
import ListHeader from '@/components/list-header.vue'
import { getGoodsListApi, deleteAllApi, shipApi, companyApi, refundApi, shipinfoApi, exportExcelApi } from '@/api/order'
import { toast } from '@/utils/elnotification'
import FromDrawer from '@/components/from-drawer.vue'
import { ElMessageBox } from 'element-plus'
import dayjs from 'dayjs'

// 订单类型：all全部，nopay待支付，noship待发货，shiped待收货，received已收货，finish已完成，closed已关闭，refunding退款中
const tabsList = [
  { label: '全部', name: 'all' },
  { label: '待支付', name: 'nopay' },
  { label: '待发货', name: 'noship' },
  { label: '待收货', name: 'shiped' },
  { label: '已收货', name: 'received' },
  { label: '已完成', name: 'finish' },
  { label: '已关闭', name: 'closed' },
  { label: '退款中', name: 'refunding' }
]

//总页数
const total = ref(0)

//当前页数
const currentPage = ref(1)

//页面loading
const loading = ref(false)

//默认激活tabs
const activeName = ref('all')

//tabs切换
const onTabChange = (val) => {
  activeName.value = val
  getGoodsList()
}

// 搜索栏
const searchForm = ref({
  no: null,
  starttime: null,
  endtime: null,
  name: null,
  phone: null
})

//商品分类显示条件
const isShowCategorySelect = ref(true)

//搜索
const onSearch = () => {
  getGoodsList(1)
}

//重置
const onReset = () => {
  //清空搜索栏
  searchForm.value = {
    title: '',
    category_id: null
  }
  //重新获取数据
  getGoodsList(1)
}

//table数据
const tableData = ref([])

//获取tableData数据
const getGoodsList = async (p = null) => {
  //传递进来的页码
  if (typeof p === 'number') {
    currentPage.value = p
  }

  //开启页面加载效果
  loading.value = true

  try {
    //调用接口
    const res = await getGoodsListApi(currentPage.value, {
      tab: activeName.value,
      no: searchForm.value.no,
      starttime: searchForm.value.starttime,
      endtime: searchForm.value.endtime,
      name: searchForm.value.name,
      phone: searchForm.value.phone
    })
    //赋值页面数
    total.value = res.totalCount
    //赋值tableData
    tableData.value = res.list
  } catch (error) {
  } finally {
    //关闭页面加载效果
    loading.value = false
  }
}

//存储全选/多选的数据id
const ids = ref([])

//全选/多选事件
const onSelectionChange = (val) => {
  ids.value = val.map((item) => item.id)
}

//批量删除
const onDeleteAll = async () => {
  if (ids.value.length === 0) return toast('请选择所需要操作的数据', 'error')
  try {
    await deleteAllApi(ids.value)
    toast('批量删除成功')
    getGoodsList(1)
  } catch (error) {
    toast('仅供演示，来到此步表示操作成功', 'error')
  } finally {
    ids.value = []
  }
}

//查看订单抽屉
const fromDrawerRef = ref(null)

//存储订单详情信息
const orderData = ref([])

//订单详情
const onOrderDetails = (row) => {
  fromDrawerRef.value.open()
  orderData.value = row
}

//订单发货抽屉
const fromDrawerRef2 = ref(null)

//订单发货表单
const shipform = ref({
  express_company: null,
  express_no: null
})

//快递公司数据
const companyData = ref([])

//发货订单id
const shipId = ref(0)

//订单发货
const onShipments = async (row) => {

  const res = await companyApi()
  shipId.value = row.id
  companyData.value = res.list
  fromDrawerRef2.value.open()


}

// 确定发货
const onShipSubmit = async () => {
  console.log(555);
  fromDrawerRef2.value.showLoading()
  try {
    await shipApi(shipId.value, {
      express_company: shipform.value.express_company,
      express_no: shipform.value.express_no
    })
    toast('发货成功')
  } catch (error) {
    toast('演示环境(发货成功)', 'error')
  } finally {
    fromDrawerRef2.value.hideLoading()
  }
}

//同意退款
const onAgree = async (id, num) => {
  const res = await ElMessageBox.confirm(
    '是否要同意该订单退款??',
    'Warning',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
  if (res === 'confirm') {

    try {
      await refundApi(id, {
        agree: num
      })
      toast('退款成功')
      getGoodsList()
    } catch (error) {
      toast('演示环境(退款成功)', 'error')
    }
  }

}

//拒绝退款
const onRefusal = async (id, num) => {
  const { value, action } = await ElMessageBox.prompt('请输入拒绝的理由', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
  })
  if (action === 'confirm') {

    try {
      await refundApi(id, {
        agree: num,
        disagree_reason: value
      })
      toast('已拒绝成功')
      getGoodsList()
    } catch (error) {
      toast('演示环境(已拒绝成功)', 'error')
    }
  }
}

//查看物流详情抽屉
const fromDrawerRef3 = ref(null)


//存储物流信息
const shipInfoData = ref([])

//查看物流
const onWatchLogistics = async (id) => {

  const res = await shipinfoApi(id)

  if (res.status === 300) return toast('订单号已失效')

  shipInfoData.value = res.result

  console.log(res);
  fromDrawerRef3.value.open()

}

//导出订单数据表格
const excelform = ref({
  tab: "",
  starttime: "",
  endtime: ''

})

//时间范围
const timeVal = ref([])
watch(() => timeVal.value, (val) => {
  excelform.value.starttime = val[0]
  excelform.value.endtime = val[1]
})

//导出订单抽屉
const fromDrawerRef4 = ref(null)


//打开导出表格抽屉
const exportExeclShow = () => {
  excelform.value = {
    tab: "",
    starttime: "",
    endtime: ''
  }
  timeVal.value = []
  fromDrawerRef4.value.open()
}


//导出下载表格
const exportExecl = async () => {
  const res = await exportExcelApi(excelform.value.tab, {
    starttime: excelform.value.starttime,
    endtime: excelform.value.endtime
  })
  let url = window.URL.createObjectURL(new Blob([res]))  //生成一个blob链接
  let link = document.createElement("a")  //创建一个a标签
  link.style.display = "none" //隐藏a标签
  link.href = url //将blob链接赋值给a标签的href属性
  let filename = (new Date()).getTime() + ".xlsx"  //文件名及其格式
  link.setAttribute("download", filename)  //下载事件
  document.body.appendChild(link) //添加a元素到body中
  link.click(); // 点击下载
}



onMounted(() => {
  getGoodsList()
})
</script>

<template>
  <div>
    <!-- tab切换 -->
    <el-tabs v-model="activeName" @tab-change="onTabChange">
      <el-tab-pane :label="item.label" :name="item.name" v-for="(item, index) in tabsList" :key="index"></el-tab-pane>
    </el-tabs>
    <el-card shadow="never" class="border-0">
      <!-- 搜索 -->
      <el-form :model="searchForm" label-width="120px" ref="searchFormRef">
        <el-row :gutter="20">
          <el-col :span="8" :offset="0">
            <el-form-item label="商品编号">
              <el-input v-model="searchForm.no" placeholder="请输入商品编号" clearable />
            </el-form-item>
          </el-col>

          <el-col :span="8" :offset="0">
            <el-form-item label="收货人" v-if="isShowCategorySelect">
              <el-input v-model="searchForm.name" placeholder="请输入收货人" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="8" :offset="0">
            <el-form-item label="手机号" v-if="isShowCategorySelect">
              <el-input v-model="searchForm.phone" placeholder="请输入手机号" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="8" :offset="0">
            <el-form-item label="开始时间" v-if="isShowCategorySelect">
              <el-date-picker v-model="searchForm.starttime" type="date" placeholder="请选择开始时间"
                value-format="YYYY-MM-DD" />
            </el-form-item>
          </el-col>
          <el-col :span="8" :offset="0">
            <el-form-item label="结束时间" v-if="isShowCategorySelect">
              <el-date-picker value-format="YYYY-MM-DD" v-model="searchForm.endtime" type="date" placeholder="请选择结束时间" />
            </el-form-item>
          </el-col>
          <el-col :span="8" :offset="0">
            <div class="flex items-center justify-end">
              <el-button type="primary" @click="onSearch">搜索</el-button>
              <el-button @click="onReset">重置</el-button>
            </div>
          </el-col>
        </el-row>
      </el-form>
      <!-- 新增/删除/上下架/刷新 -->
      <ListHeader :create="false" delete @deleteAll="onDeleteAll" export @export="exportExeclShow"></ListHeader>
      <!-- 表单部分 -->
      <el-table :data="tableData" stripe style="width: 100%" @selection-change="onSelectionChange" v-loading="loading">
        <el-table-column type="selection" width="55" />
        <el-table-column label="商品" width="400">
          <template #default="{ row }">
            <div>
              <div class="flex text-sm">
                <h6>
                  订单号:
                  <p>{{ row.no }}</p>
                </h6>
                <h6 class="ml-6">
                  下单时间:
                  <p>{{ row.create_time }}</p>
                </h6>
              </div>
              <div class="flex items-center mt-2">
                <el-image class="rounded mr-2" style="width: 40px; height: 40px"
                  :src="row.order_items[0].goods_item ? row.order_items[0].goods_item.cover : ''" />
                <p class="text-blue-500">
                  {{ row.order_items[0].goods_item ? row.order_items[0].goods_item.title : '' }}
                </p>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="total_price" label="实付款" align="center" />
        <el-table-column label="买家" align="center">
          <template #default="{ row }">
            <div>
              <p>{{ row.user.username }}</p>
              <p class="text-sm">(用户ID:{{ row.user.id }})</p>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="交易状态">
          <template #default="{ row }">
            <div>
              付款状态：
              <el-tag v-if="row.payment_method == 'wechat'" type="success" size="small">微信支付</el-tag>
              <el-tag v-else-if="row.payment_method == 'alipay'" size="small">支付宝支付</el-tag>
              <el-tag v-else type="info" size="small">未支付</el-tag>
            </div>
            <div>
              发货状态：
              <el-tag :type="row.ship_data ? 'success' : 'info'" size="small">{{
                row.ship_data ? '已发货' : '未发货'
              }}</el-tag>
            </div>
            <div>
              收货状态：
              <el-tag :type="row.ship_status == 'received' ? 'success' : 'info'" size="small">{{
                row.ship_status == 'received' ? '已收货' : '未收货'
              }}</el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="right">
          <template #default="{ row }">
            <el-button text type="primary" size="small" @click="onOrderDetails(row)">订单详情</el-button>
            <el-button text type="primary" size="small"
              v-if="row.payment_method == 'wechat' && activeName == 'all' || row.payment_method == 'alipay' && activeName == 'all' || activeName == 'noship'"
              @click="onShipments(row)">订单发货</el-button>
            <el-button text type="primary" size="small" @click="onAgree(row.id, 1)"
              v-if="activeName == 'refunding'">同意退款</el-button>
            <el-button text type="primary" size="small" @click="onRefusal(row.id, 0)"
              v-if="activeName == 'refunding'">拒绝退款</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="flex justify-center justify-center mt-5">
        <el-pagination background layout="prev, pager, next" :total="total" @current-change="getGoodsList"
          :current-page="currentPage" />
      </div>
    </el-card>

    <!-- 查看订单详情 -->
    <FromDrawer ref="fromDrawerRef" title="订单详情" :buttom="false">
      <!-- 订单信息 -->
      <el-card class="mb-3" shadow="never" v-if="orderData.payment_no">
        <template #header>
          <div class="card-header">
            <h3 class="text-sm font-bold">订单信息</h3>
          </div>
        </template>
        <div>
          <p class="text-sm my-7 flex">
          <h2 class="w-15">订单号</h2><span class="ml-8">{{ orderData.payment_no }}</span></p>
          <p class="text-sm my-7 flex">
          <h2 class="w-15">付款方式</h2><span class="ml-8">{{ orderData.payment_method }}</span></p>
          <p class="text-sm my-7 flex">
          <h2 class="w-15">创建时间</h2><span class="ml-8">{{ orderData.create_time }}</span></p>
          <p class="text-sm my-7 flex">
          <h2 class="w-15">付款时间</h2>
          <span class="ml-8">{{ dayjs.unix(orderData.paid_time).format('YYYY-MM-DD HH:mm: ss') }}</span>
          </p>

        </div>
      </el-card>
      <!-- 发货信息 -->
      <el-card class="mb-3" shadow="never" v-if="orderData.ship_data">
        <template #header>
          <div class="card-header">
            <h3 class="text-sm font-bold">发货信息</h3>
          </div>
        </template>
        <div>
          <p class="text-sm my-7 flex">
          <h2 class="w-15">物流公司</h2><span class="ml-8">{{ orderData.ship_data.express_company }}</span>
          </p>
          <p class="text-sm my-7 flex items-center">
          <h2 class="w-15">运单号</h2><span class="ml-8">{{ orderData.ship_data.express_no }}</span> <el-button text
            type="primary" size="small" @click="onWatchLogistics(orderData.id)">查看物流</el-button> </p>
          <p class="text-sm my-7 flex">
          <h2 class="w-15">发货时间</h2>
          <span class="ml-8">{{ dayjs.unix(orderData.ship_data.express_time * 1.03).format('YYYY-MM-DD HH: mm: ss')
          }}</span>
          </p>
        </div>
      </el-card>
      <!-- 商品信息 -->
      <el-card class="mb-3" shadow="never" v-if="orderData.order_items">
        <template #header>
          <div class="card-header">
            <h3 class="text-sm font-bold">商品信息</h3>
          </div>
        </template>
        <div class="flex items-center" v-for="item, index in orderData.order_items" :key="index">
          <el-image class="rounded" style="width: 60px; height: 60px" :src="item.goods_item.cover" />
          <div class="text-sm ml-2">
            <p>{{ item.goods_item.title }}</p>
            <el-tag class="my-1" type="info" size="small"> {{ orderData.order_items[index].goods_skus.skus[0].value }},{{
              orderData.order_items[index].goods_skus.skus[1].value }}</el-tag>
            <p> <span class="text-rose-500 font-bold">￥{{ orderData.order_items[index].price }}</span> <span
                class="ml-2 text-xs text-gray-500">x{{ orderData.order_items[index].num }}</span> </p>
          </div>
          <div>
          </div>
        </div>
        <p class="mt-5 text-sm">成交价 <span class="text-rose-500 font-bold ml-8">￥0.10</span></p>
      </el-card>
      <!-- 收货信息 -->
      <el-card class="mb-3" shadow="never" v-if="orderData.address">
        <template #header>
          <div class="card-header">
            <h3 class="text-sm font-bold">收货信息</h3>
          </div>
        </template>
        <div>
          <p class="text-sm my-7 flex items-center">
          <h2 class="w-15">收货人</h2><span class="ml-8">{{ orderData.address.name }}</span> </p>
          <p class="text-sm my-7 flex">
          <h2 class="w-15">联系方式</h2><span class="ml-8">{{ orderData.address.phone }}</span></p>
          <p class="text-sm my-7 flex">
          <h2 class="w-15">收货信息</h2><span class="ml-8">{{ orderData.address.province }} {{ orderData.address.city }}{{
            orderData.address.district }}</span></p>
        </div>
      </el-card>
    </FromDrawer>

    <!-- 发货 -->
    <FromDrawer ref="fromDrawerRef2" title="订单发货" @submit="onShipSubmit">
      <el-form :model="shipform" label-width="120px">
        <el-form-item label="快递公司">
          <el-select v-model="shipform.express_company" placeholder="请选择快递公司">
            <el-option v-for="item in companyData" :key="item.id" :label="item.name" :value="item.name" />
          </el-select>
        </el-form-item>
        <el-form-item label="快递单号">
          <el-input v-model="shipform.express_no" placeholder="请输入快递单号" />
        </el-form-item>
      </el-form>
    </FromDrawer>

    <!-- 物流单 -->
    <FromDrawer ref="fromDrawerRef3" title="物流详情" :buttom="false" size="30%">
      <el-card shadow="never" class="border-0 text-[#303133]">
        <template #header>
          <div class="flex ">
            <el-image style="width: 60px; height: 60px" class="rounded" :src="shipInfoData.logo" />
            <div class="ml-2 text-sm">
              <p class="mb-2">物流公司：{{ shipInfoData.typename }}</p>
              <p>物流单号：{{ shipInfoData.number }}</p>
            </div>
          </div>
        </template>
        <el-timeline>
          <el-timeline-item v-for="(activity, index) in shipInfoData.list" :key="index" :timestamp="activity.time">
            {{ activity.status }}
          </el-timeline-item>
        </el-timeline>
      </el-card>

    </FromDrawer>

    <!-- 导出订单 -->
    <FromDrawer ref="fromDrawerRef4" title="导出订单" :buttom="false">
      <el-form :model="excelform" label-width="120px">
        <el-form-item label="订单类型">
          <el-select v-model="excelform.tab" placeholder="请选择">
            <el-option v-for="item in tabsList" :key="item.value" :label="item.label" :value="item.name" />
          </el-select>
        </el-form-item>
        <el-form-item label="时间范围">
          <el-date-picker value-format="YYYY-MM-DD" :editable="false" v-model="timeVal" type="daterange"
            range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" />
        </el-form-item>
        <el-form-item> <el-button type="primary" @click="exportExecl">导出</el-button></el-form-item>

      </el-form>
    </FromDrawer>
  </div>
</template>

<style scoped></style>
